<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手1</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .chat-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .chat-history {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            background-color: #fafafa;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            max-width: 80%;
            clear: both;
            word-wrap: break-word;
        }
        .user-message {
            background-color: #007bff;
            color: white;
            float: right;
        }
        .ai-message {
            background-color: #e9ecef;
            color: black;
            float: left;
        }
        /* 清除浮动影响 */
        .chat-history::after {
            content: "";
            display: table;
            clear: both;
        }
        .input-area {
            display: flex;
            gap: 10px;
        }
        #user-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        #send-btn {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        #send-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .typing-indicator {
            color: #6c757d;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>AI聊天助手</h1>
        <div id="chat-history" class="chat-history"></div>
        <div class="input-area">
            <input type="text" id="user-input" placeholder="输入你的问题..." />
            <button id="send-btn">发送</button>
        </div>
    </div>

    <script>
        const chatHistory = document.getElementById('chat-history');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');
        let currentAiMessage = null;

        function addMessage(message, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
            messageDiv.textContent = message;
            chatHistory.appendChild(messageDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
            return messageDiv;
        }

        function showTyping() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message ai-message typing-indicator';
            typingDiv.id = 'typing-indicator';
            typingDiv.textContent = '正在思考中...';
            chatHistory.appendChild(typingDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function hideTyping() {
            const typingIndicator = document.getElementById('typing-indicator');
            if (typingIndicator) {
                typingIndicator.remove();
            }
        }

        function createAiMessageElement() {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ai-message';
            chatHistory.appendChild(messageDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
            return messageDiv;
        }

function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;

    // 添加用户消息
    addMessage(message, true);
    userInput.value = '';
    sendBtn.disabled = true;

    // 显示正在输入指示器
    showTyping();

    // 创建AI消息元素
    let aiMessageElement = null;
    let fullResponse = '';

    try {
        // 使用 Fetch API 发送 POST 请求并处理流式响应
        fetch('/api/v1/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                message: message,
                session_id: 'default'
            })
        }).then(response => {
            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            // 隐藏正在输入指示器
            hideTyping();
            aiMessageElement = createAiMessageElement();

            function readStream() {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        sendBtn.disabled = false;
                        userInput.focus();
                        return;
                    }

                    const text = decoder.decode(value);
                    const lines = text.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6); // 移除 'data: ' 前缀
                            if (data === '[DONE]') {
                                sendBtn.disabled = false;
                                userInput.focus();
                                return;
                            }

                            try {
                                const jsonData = JSON.parse(data);
                                if (jsonData.error) {
                                    aiMessageElement.textContent += `\n错误: ${jsonData.error}`;
                                    sendBtn.disabled = false;
                                    userInput.focus();
                                    return;
                                } else {
                                    fullResponse += jsonData.content;
                                    aiMessageElement.textContent = fullResponse;
                                    chatHistory.scrollTop = chatHistory.scrollHeight;
                                }
                            } catch (e) {
                                console.error('解析JSON失败:', e);
                            }
                        }
                    }

                    readStream(); // 继续读取流
                }).catch(error => {
                    hideTyping();
                    if (!aiMessageElement) {
                        aiMessageElement = addMessage(`网络错误: ${error.message}`, false);
                    } else {
                        aiMessageElement.textContent += `\n网络错误: ${error.message}`;
                    }
                    sendBtn.disabled = false;
                    userInput.focus();
                });
            }

            readStream(); // 开始读取流
        }).catch(error => {
            hideTyping();
            addMessage(`请求失败: ${error.message}`, false);
            sendBtn.disabled = false;
            userInput.focus();
        });
    } catch (error) {
        hideTyping();
        addMessage(`发生错误: ${error.message}`, false);
        sendBtn.disabled = false;
        userInput.focus();
    }
}


        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 添加欢迎消息
        window.onload = () => {
            addMessage('你好！我是AI助手，有什么我可以帮你的吗？', false);
            userInput.focus();
        };
    </script>
</body>
</html>